﻿using Microsoft.EntityFrameworkCore;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    public class BiSupplierDal
    {
        private readonly AppDbContext _dbContext;

        public BiSupplierDal(AppDbContext dbContext)
        {
            _dbContext = dbContext;
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="data">实体</param>
        /// <returns>结果</returns>
        public async Task<int> CreateAsync(BiSupplier data)
        {
            // 新增实体到数据库集
            _dbContext.biSupplier.Add(data);
            // 保存更改
            return await _dbContext.SaveChangesAsync();
        }

        /// <summary>
        /// 根据ID查询
        /// </summary>
        /// <param name="supplierId">ID</param>
        /// <returns>用户列表</returns>
        public async Task<BiSupplier> GetByIdAsync(long supplierId)
        {
            // 根据ID查询
            var supplier = await _dbContext.biSupplier.FirstOrDefaultAsync(g => g.SupplierId == supplierId);
            if (supplier != null)
            {
                // 确保 Status 为字符串（若数据库存储为数字，需显式转换）
                supplier.Status = supplier.Status?.ToString() ?? "0";
            }
            return supplier;
        }

        /// <summary>
        /// 查询所有
        /// </summary>
        /// <returns>用户列表</returns>
        public async Task<List<BiSupplier>> GetAllAsync()
        {
            // 查询所有并转换为列表
            return await _dbContext.biSupplier.ToListAsync();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="date">包含更新信息</param>
        public async Task<int> UpdateAsync(BiSupplier date)
        {
            // 标记实体为修改状态
            _dbContext.Entry(date).State = EntityState.Modified;

            // 排除不需要更新的字段
            _dbContext.Entry(date).Property(x => x.CreateBy).IsModified = false;
            _dbContext.Entry(date).Property(x => x.CreateTime).IsModified = false;
            _dbContext.Entry(date).Property(x => x.SupplierCode).IsModified = false; // 编码通常也不应该修改

            // 保存更改
            return await _dbContext.SaveChangesAsync();
        }

        /// <summary>
        /// 根据ID删除
        /// </summary>
        /// <param name="supplierId">ID</param>
        public async Task<int> DeleteAsync(long supplierId)
        {
            var data = await GetByIdAsync(supplierId);
            if (data != null)
            {
                _dbContext.biSupplier.Remove(data);
                return await _dbContext.SaveChangesAsync();
            }
            return 0;
        }
    }
}
